var jwt = require("jsonwebtoken");
var $cookie = require('./cookieUtil.js');
var writeJson = require('./jsonUtil.js');

var secretOrPrivateKey = "demo"
var createToken = function(userId){
  var content ={userId:userId}; // 要生成token的主题信息
  // 这是加密的key（密钥）
  var token = jwt.sign(content, secretOrPrivateKey, {
          expiresIn: 60*60  // 1小时过期
      });
  return token;
}

var verifyToken = function(rq, rs, next){
  // var token = rq.body.token || rq.query.token || rq.headers["x-access-token"]; // 从body或query或者header中获取token
    let cookie = $cookie(rq.headers.cookie);
    let token = cookie.token;
    jwt.verify(token, secretOrPrivateKey, function (err, decode) {
            if (err) {  //  时间失效的时候/ 伪造的token
               rs.json(writeJson('token.fault', err.message))
              console.log(err);
            } else {
                rq.decode = decode;
                console.log(decode);   // today  is  a  good  day
                next();
            }
        })
}

module.exports = { createToken, verifyToken};
